package com.imufe.springbootshiro.shiro;

import com.imufe.springbootshiro.domain.User;
import com.imufe.springbootshiro.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @Auther: sunYong
 * @Date: 2019/2/7 23:42
 * @Description: ${package_name}
 */
public class UserRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    /*执行授权逻辑*/
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行认证逻辑");
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
//添加资源的授权字符串
//        simpleAuthorizationInfo.addStringPermission("user:add");
//到数据库查询当前登录用户的授权字符串
        Subject subject = SecurityUtils.getSubject();
        User user = (User)subject.getPrincipal();
        User dbUser = userService.findById(user.getId());
        simpleAuthorizationInfo.addStringPermission(dbUser.getPerms());
        return simpleAuthorizationInfo;
    }

    /*执行认证逻辑*/
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行认证逻辑");

//        假设用户名和密码
        String username="admin";
        String password="123";
//        编写shiro判断逻辑，判断用户名和密码
//        1、判断同户名
//        2、判断密码
        UsernamePasswordToken token = (UsernamePasswordToken)authenticationToken;
        User user = userService.findByName(token.getUsername());
        if(user == null){
//            用户名不存在
            return null;  //shiro底层会抛出UnknowAccountException
        }

//        2、判断密码
        return new SimpleAuthenticationInfo(user,user.getPassword(),"");
    }
}
